<template>
  <div>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="filterForm" label-width="80px" ref="filterForm">

        <el-form-item>
          <el-button @click="handleAdd">新增</el-button>
          <el-button @click="goback">返回房源列表</el-button>
        </el-form-item>
      </el-form>
    </el-col>


    <!--表格-->
    <el-table :data="arrList" size="medium" stripe highlight-current-row v-loading="loading" style="width: 100%;"
              @sort-change="handleSort">
      <el-table-column prop="id" label="id" width="100" sortable fixed="left"></el-table-column>
      <el-table-column prop="url" label="轮播图">
        <template slot-scope="scope">
          <img :src="scope.row.url" @mouseover="showBigPic(scope.row.url)"
               @mouseout="closeBigPic()" width="100"/>
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="更新时间" sortable></el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--add-->

    <el-dialog title="多张上传" :visible.sync="addVisible" :close-on-click-modal="false"
               style="display: none">
      <el-form label-width="100px">
        <el-form-item>
          <el-upload
                  class="avatar-uploader"
                  :action="uploadAction"
                  multiple
                  :limit="10"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-success="addUploadSuccess"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
            <!--<i class="el-icon-plus avatar-uploader-icon"></i>-->
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialogImgList">取消</el-button>
        <el-button type="primary" @click.native="imglistSubmit" :loading="editLoading">提交</el-button>
      </div>
      <el-dialog :visible.sync="dialogVisible" append-to-body width="375px">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-dialog>


    <!--update-->
    <el-dialog :title="editFormTitle" :visible.sync="editFormVisible" :close-on-click-modal="false"
               style="display: none">
      <el-form :model="editForm" label-width="100px" ref="editForm" :rules="editFormRules">

        <el-form-item>
          <div class="avatar-uploader">
            <div @click="showuploadimg" class="el-upload">
              <img v-if="editForm.url" :src="editForm.url" class="avatar">
              <i v-else="" class="el-icon-plus avatar-uploader-icon"></i>
            </div>
          </div>

          <span v-show="false">列表图尺寸:686*388(宽*高)</span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="closeDialog">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <div style="position: fixed;top:35%;left: 60%;z-index: 999" v-show="bigPic != ''">
      <img style="max-width: 400px" :src="bigPic"/>
    </div>
    <el-dialog title="上传图片" :visible.sync="showUploadimg" :close-on-click-modal="false">
      <div class="imgUpwrapper">
        <vueCropper class="uploadwrapper"
                    ref="cropper"
                    :img="uploadImgOption.img"
                    :outputSize="uploadImgOption.size"
                    :outputType="uploadImgOption.outputType"
                    :info="uploadImgOption.info"
                    :canScale="uploadImgOption.canScale"
                    :autoCrop="uploadImgOption.autoCrop"
                    :autoCropWidth="uploadImgOption.autoCropWidth"
                    :autoCropHeight="uploadImgOption.autoCropHeight"
                    :fixed="uploadImgOption.fixed"
                    :fixedNumber="uploadImgOption.fixedNumber"
        ></vueCropper>
        <div class="buttons">
          <label class="btn" for="uploads">选择图片</label>
          <input type="file" id="uploads" style="position:absolute; clip:rect(0 0 0 0);"
                 accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">

        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.native="finish('blob')" :loading="editLoading">上传图片</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    URI_GETBANNER,
    URI_UPLOAD,
    URI_POSTBANNNERINFO,
    URI_DELETEBANNER,
    URI_POSTMOREBANNERINFO
  } from 'src/const/uri';
  import VueCropper from 'vue-cropper';

  export default {
    name: "banner",
    components: {VueCropper},
    data() {
      return {
        /**/
        uploadImgOption: {
          img: '',
          info: true,
          size: 1,
          outputType: 'png',
          canScale: true,
          autoCrop: true,
          // 只有自动截图开启 宽度高度才生效
          // autoCropWidth: 500,
          // autoCropHeight: 250,
          // 开启宽度和高度比例
          fixed: true,
          fixedNumber: [1, 1.32960],
        },
        formData: new FormData(),
        previews: {},
        fileName: '',
        showUploadimg: false,
        /**/
        filterForm: {},
        bigPic: '',
        loading: false,
        houseId: this.$route.params.houseId,
        arrList: [],
        editFormTitle: '',
        editFormVisible: false,
        editForm: {},
        editLoading: false,
        addVisible: false,
        editFormRules: {
          desc: [
            {required: true, message: '请输入标题', trigger: 'blur'}
          ],
          from: [
            {required: true, message: '请输入标题', trigger: 'blur'}
          ],

        },
        uploadAction: URI_UPLOAD,
        fileList: [],
        dialogVisible: false,
        dialogImageUrl: ''
      }
    },
    mounted() {
      this.initData()
    },
    methods: {
      initData() {
        this.loading = true;
        this.$ajax.get(URI_GETBANNER, {
          id: this.houseId
        }, res => {
          this.loading = false;
          this.arrList = res.data;
        });
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 10 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      addUploadSuccess(response, file, fileList) {
        //console.log(fileList);
        //this.uploadImgList.push(response.data);
        this.fileList = fileList;
      },
      handleRemove(file, fileList) {
        this.fileList = fileList;
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      imglistSubmit() {
        let formData = [];
        this.fileList.forEach((val, index) => {
          let arr = {type_house_id: this.houseId, url: val.response.data};
          formData.push(arr);
        });
        this.$ajax.post(URI_POSTMOREBANNERINFO, {formData: formData}, res => {
          this.$message.success(res.message);
          this.addVisible = false;
          this.fileList = [];
          this.initData();
        });

      },

      /**/
      showuploadimg() {
        this.showUploadimg = true;
        //console.log(this.editForm.url);
        this.uploadImgOption.img = this.editForm.url;
        //this.uploadImgOption.img= 'http://ofyaji162.bkt.clouddn.com/bg1.jpg';
      },
      uploadImg(e, num) {
        var that = this;
        //上传图片
        // this.option.img
        var file = e.target.files[0];
        //console.log(file);
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
          alert('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种')
          return false
        }
        var reader = new FileReader()
        reader.onload = (e) => {
          let data
          if (typeof e.target.result === 'object') {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]))
          } else {
            data = e.target.result
          }
          if (num === 1) {
            console.log(file.name);
            that.fileName = file.name;
            this.uploadImgOption.img = data
          }
        }
        // 转化为base64
        //reader.readAsDataURL(file)
        // 转化为blob
        reader.readAsArrayBuffer(file)
      },
      finish(type) {
        var that = this;
        if (type === 'blob') {
          this.$refs.cropper.getCropBlob((data) => {
            var blob = data;
            let file = new File([blob], that.fileName || '.jpg');
            that.formData.append('file', file);
            this.$ajax.uploadForm(URI_UPLOAD, {}, res => {
              console.log(res);
              this.showUploadimg = false;
              this.editForm.url = res.data;
              this.uploadImgOption.img = '';
            }, error => {
            }, this.formData);
          })
        } else {
          this.$refs.cropper.getCropData((data) => {
            //test.location.href = data
            console.log(data);
          })
        }
      },
      /**/
      handleAdd() {
        this.addVisible = true;
        // this.editForm = {};
        // if (this.$refs['editForm']) {
        //   this.$refs['editForm'].clearValidate();
        // }
        // this.editForm = {url: ''};
        //
        // this.editFormTitle = '新增';
        // this.editFormVisible = true;
      },
      goback() {
        this.$router.push('/houseList')
      },
      handleSort() {
      },
      handleEdit(index, row) {
        if (this.$refs['editForm']) {
          this.$refs['editForm'].clearValidate();
        }
        this.editForm = Object.assign({}, row);
        this.editFormTitle = '更新';
        this.editFormVisible = true;
      },
      handleDelete(index, row) {
        //console.log(row);
        this.$ajax.get(URI_DELETEBANNER, {
          id: row.id
        }, res => {
          this.$message.success(res.data);
          this.initData();
        });
      },
      editSubmit() {
        console.log(this.editForm)
        if (!this.editForm.url) {
          this.$message.error('请上上传房源主图!');
          return;
        }
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.editForm.type_house_id = this.houseId;
            this.$ajax.post(URI_POSTBANNNERINFO, {
              formData: this.editForm,
            }, res => {
              this.$message.success(res.message);
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.initData();
            });
          } else {
            this.$message.error('表单验证失败!');
          }
        })


      },
      closeDialog() {
        this.editFormVisible = false;
        this.editForm = {};
      },
      closeDialogImgList() {
        this.addVisible = false;
      },
      showBigPic(pic) {
        this.bigPic = pic;
      },
      closeBigPic() {
        this.bigPic = '';
      },
      handleAvatarSuccess(res, file) {
        if (res.code === 0) {
          this.editForm.url = res.data;
          console.log(this.editForm);
        } else {
          this.$message.error('上传失败');
        }

      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 5;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 5MB!');
        }
        return isJPG && isLt2M;
      },
    }

  }
</script>

<style>

  .toolbar {
    background: #f2f2f2;
    padding: 10px;
    margin: 10px 0px;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .el-upload--text {
    width: auto;
    height: auto;
  }

  .avatar {
    width: 300px;
    height: auto;
    display: block;
  }

  .imgUpwrapper {
    width: 375px;
    height: 667px;
    margin: 0 auto;
  }

  .imgUpwrapper .btn {
    display: inline-block;
    line-height: 1;
    white-space: nowrap;
    cursor: pointer;
    background: #fff;
    border: 1px solid #c0ccda;
    color: #1f2d3d;
    text-align: center;
    box-sizing: border-box;
    outline: none;
    margin: 20px 10px 0px 0px;
    padding: 9px 15px;
    font-size: 14px;
    border-radius: 4px;
    color: #fff;
    background-color: #50bfff;
    border-color: #50bfff;
    transition: all .2s ease;
    text-decoration: none;
    user-select: none;
  }

</style>